const env = require('./env.js');

const _toast = (option, isSuccess) => {
  const DEFAULT = {
    title: "操作失败",
    icon: "none",
    duration: 2000
  }

  if (typeof option != 'object') {
    option = { title: option };
  }

  option = Object.assign({}, DEFAULT, option);

  wx.showToast({
    title: option.title || (isSuccess ? "操作成功" : "操作失败"),
    icon: isSuccess ? 'success' : 'none',
    duration: option.duration,
    success() {
      setTimeout(() => option.callback && option.callback(), option.duration);
    }
  });
};


const Helper = {
  isDevelopment() {
    return env === 'DEVELOPMENT';
  },
  log(...rest) {
    this.isDevelopment() && console.log(...rest);
  },
  showLoading(title = "加载中...", mask = true) {
    wx.showLoading({ title, mask })
  },
  hideLoading() {
    wx.hideLoading();
  },
  toastErr(option) {
    const isSuccess = false;
    _toast(option, isSuccess);
  },
  toastSuc(option) {
    const isSuccess = true;
    _toast(option, isSuccess);
  },
  alert(sender) {
    const DEFAULT = {
      title: "百得掌柜",
      showCancel: false,
      confirmColor: "#29233B",
      confirmText: "知道了"
    };
    const isObject = typeof sender === "object";
    sender = Object.assign({}, DEFAULT, isObject ? sender : { content: sender + "" });

    wx.showModal(sender);
  },
  confirm(sender) {
    const DEFAULT = {
      title: "百得掌柜"
    };
    const isObject = typeof sender === "object";
    sender = Object.assign({}, DEFAULT, isObject ? sender : { content: sender + "" });

    return new Promise(resolve => {
      wx.showModal(Object.assign({
        success: res => resolve(res.confirm)
      }, sender));
    })
  },
  settingStorage(key, options) {
    try{
      wx.setStorageSync(key, options);
    } catch (e) {
      console.log(`${key}存入缓存出错: `, e);
    }
  },
  gettingStorage(key) {
    try{
      return wx.getStorageSync(key);
    } catch (e) {
      console.log(`${key}读取缓存出错: `, e);
    }
  },
  trim(str) {
    return str.replace(/^\s*/, '').replace(/\s*$/, '');
  },
  wxLogin() {
    const helper = this;
    let isNotExpired = false;

    return new Promise((resolve, reject) => {
      wx.checkSession({
        success() {
          helper.log("登录session未失效");
          isNotExpired = true;
          return resolve(isNotExpired);
        },
        fail() {
          helper.log("登录session已失效，重新登录");
          wx.login({
            success(res) {
              if (res.code) {
                return resolve(res.code);
              } else {
                return reject('获取用户登录态失败！' + res.errMsg);
              }
            }
          });
        }
      });
    });
  },
  breakSignal({ isError, data = null }) {
    return Promise.reject({ isError, data });
  },
  formatPx(px) {
    let limitTimes = 10;
    let counter = 0;
    let isValid = function () {
      return !!wx.getStorageSync('kScreenW');
    };
    let transfrom = function (px) {
      px = px * wx.getStorageSync('kScreenW');
      px = Math.round(px * 100) / 100;
      return px;
    };

    if (isValid()) {
      return transfrom(px);
    } else {
      let timer = setInterval(() => {
        if (isValid()) {
          clearInterval(timer);
          return transfrom(px);
        }

        if (++counter >= limitTimes) {
          clearInterval(timer);
          console.log("单位转换失败");
          return px;
        }
      });
    }
  },
  timeMeter(interval) {
    let start = -1;
    return {
      set() {
        start = Date.now();
      },
      get() {
        let rest = Date.now() + interval - start;
        return rest > 0 ? rest : 0;
      }
    };
  },
  deepCopy(source) {
    const isValid = typeof source === "object";
    const toString = Object.prototype.toString;
    const isArray = sender => toString.call(sender) === "[object Array]";

    if (isValid) {
      let newObj = isArray(source) ? [] : {};

      for (let key in source) {
        const item = source[key];

        if (typeof item === "object") {
          newObj[key] = isArray(item) ? [] : {};

          newObj[key] = this.deepCopy(source[key]);
        } else {
          newObj[key] = source[key];
        }
      }

      return newObj;
    } else {
      console.error("expect a object");
      return false;
    }
  }
}

module.exports = Helper;